<template>
	<view class="task_item_page" :style="{ 'padding-bottom': pageType == 2 ? '202rpx' : '30rpx' }">
		<view class="task_form">
			<view class="form_item">
				<view class="form_item_label">
					<text class="must">*</text>任务名称
				</view>
				<template v-if="pageType == 1">
					<view class="input_bg show">
						{{ formData.title }}
					</view>
				</template>
				<template v-else>
					<view class="form_item_con" @click="chooseInputValue(1)">
						<text v-if="formData.title">{{ formData.title }}</text>
						<text v-else style="color: #a9aab5; font-size: 30rpx">请选择</text>
						<image src="@/static/teacher/more.png" class="more_down" mode=""></image>
					</view>
					<text v-if="isEmpty.title" class="error">请填写任务名称</text>
				</template>
			</view>

			<view class="form_item">
				<view class="form_item_label">
					<text class="must">*</text>任务有效期
				</view>
				<view class="date_range">
					<text v-if="pageType == 1">{{ formatDate1(formData.startTime, false) }}-{{
              formatDate1(formData.endTime, false)
            }}</text>
					<view v-if="pageType == 2" @click="chooseDateRange">
						<text
							v-if="formData.startTime && formData.endTime">{{ formatDate1(formData.startTime, false) }}-{{
                formatDate1(formData.endTime, false)
              }}</text>
						<text v-else style="color: #a9aab5; font-size: 30rpx">请选择</text>
						<image
							src="https://xuexiaole-1313840333.cos.ap-guangzhou.myqcloud.com/xuexiaoleClient/calendar_icon.png"
							class="calendar_icon" mode=""></image>
					</view>
				</view>
				<view v-if="isEmpty.indate" class="error">请选择发送时间</view>
			</view>

			<view class="form_item">
				<view class="form_item_label">
					<text class="must">*</text>发送时间
				</view>
				<SelectTime :isEdit="pageType == 1 ? false : true" :time="formData.sendTime"
					@getSendTime="handleGetSendTime" />
				<view v-if="isEmpty.sendTime" class="error">请选择定时发送时间</view>
			</view>

			<view class="form_item">
				<view class="form_item_label"><text class="must">*</text>选择奖励</view>
				<SelectedAward :list="tempRewardList" :maxNum="2" :isEdit="pageType == 1 ? false : true"
					@handleConfirmBtn="handleChooseAward" />
				<view v-if="isEmpty.rewardList" class="error">请选择奖励</view>
			</view>

			<view class="form_item">
				<view class="form_item_label">
					<text class="must">*</text>发送对象
				</view>
				<view class="form_item_con" @click="chooseInputValue(2)">
					<template v-if="pageType == 1">
						<text>共计 {{ formData.stuNum }} 人</text>
					</template>
					<template v-if="pageType == 2">
						<text v-if="formData.stuIdList?.length > 0">共计 {{ formData.stuIdList?.length }} 人</text>
						<text v-else style="color: #a9aab5; font-size: 30rpx">请选择</text>
					</template>
					<image src="@/static/teacher/more.png" class="more_down" mode=""></image>
				</view>
				<view v-if="isEmpty.stuIdList" class="error">请选择发送对象</view>
			</view>
		</view>
		<view class="footer" v-if="pageType == 2">
			<button class="btn-primary" @click="submit">发送</button>
		</view>
		<!-- 有效期 -->
		<DatePicker ref="dateRef" v-model="timeArr" @confirm="confirmDateRange" />
	</view>
</template>

<script setup>
	import {
		computed,
		nextTick,
		ref,
		watch
	} from "vue";
	import {
		onLoad,
		onShow,
		onUnload
	} from "@dcloudio/uni-app";
	import DatePicker from "@/pages/subpackage/home/Components/DatePicker/DatePicker.vue";
	import SelectTime from "@/pages/subpackage/home/Components/SelectTime/SelectTime.vue";
	import SelectedAward from "@/pages/subpackage/home/Components/SelectedAward/SelectedAward.vue";
	import {
		formatDate1
	} from "@/hooks/useGlobal.js";
	import {
		addTaskApi
	} from "@/api/index.js";
	import {
		useUserStore
	} from "@/store";

	const userStore = useUserStore();
	const dateRef = ref();
	const timeArr = ref([]); // '2024-01-01', '2024-01-31'
	const pageType = ref(); // 1查看 2新增
	// 内容是否为空
	const isEmpty = ref({
		title: false,
		indate: false,
		sendTime: false,
		rewardList: false,
		stuIdList: false,
	});

	const tempRewardList = ref([]); // 临时存储奖励
	const formData = ref({
		id: "",
		title: "",
		taskConfigId: undefined,
		targetNum: undefined,
		startTime: "",
		endTime: "",
		sendType: 1, // 1-立即发送 2-定时发送
		sendTime: "",
		rewardList: [],
		stuIdList: [],
	});

	// 选中奖励
	function handleChooseAward(val) {
		tempRewardList.value = val;
		isEmpty.value.rewardList = tempRewardList.value.length === 0;
	}
	// 发送时间
	function handleGetSendTime(val) {
		formData.value.sendType = val.sendType;
		formData.value.sendTime = val.sendTime;
		isEmpty.value.sendTime =
			formData.value.sendType === 1 ? false : !formData.value.sendTime;
	}

	function chooseInputValue(type) {
		switch (type) {
			case 1:
				// 选择任务
				uni.navigateTo({
					url: "/pages/subpackage/home/TaskManage/taskList",
				});
				break;
			case 2:
				// 发送对象
				if (userStore.userRelation === 1) {
					// 家长
					uni.navigateTo({
						url: `/pages/subpackage/home/TaskManage/patriarchSendObject?pageType=${
            pageType.value
          }&details=${encodeURIComponent(
            JSON.stringify(formData.value)
          )}&checkedList=${JSON.stringify(formData.value.stuIdList)}`,
					});
				} else if (userStore.userRelation === 2) {
					// 教师
					uni.navigateTo({
						url: `/pages/subpackage/home/TaskManage/teacherSendObject?pageType=${
            pageType.value
          }&details=${encodeURIComponent(
            JSON.stringify(formData.value)
          )}&checkedList=${JSON.stringify(formData.value.stuIdList)}`,
					});
				}

				break;
		}
	}
	// 选择有效期
	function chooseDateRange() {
		dateRef.value && dateRef.value.open();
	}

	function confirmDateRange() {
		formData.value.startTime = timeArr.value[0];
		formData.value.endTime = timeArr.value[1];
		isEmpty.value.indate = !formData.value.endTime && !formData.value.startTime;
	}
	// 提交
	async function submit() {
		isEmpty.value = {
			title: !formData.value.title,
			indate: !formData.value.startTime || !formData.value.endTime,
			sendTime: formData.value.sendType === 1 ? false : !formData.value.sendTime,
			rewardList: tempRewardList.value.length === 0,
			stuIdList: formData.value.stuIdList.length === 0,
		};
		if (
			isEmpty.value.title ||
			isEmpty.value.indate ||
			isEmpty.value.sendType ||
			isEmpty.value.rewardList ||
			isEmpty.value.stuIdList
		)
			return;
		uni.showLoading({
			title: "添加中...",
		});
		formData.value.sendTime = formData.value.sendTime ?
			formData.value.sendTime.replace(/\//g, "-") :
			"";
		if (tempRewardList.value.length > 0) {
			for (let i in tempRewardList.value) {
				formData.value.rewardList[i] = {
					rewardId: tempRewardList.value[i].rewardId,
					rewardNum: tempRewardList.value[i].rewardNum,
				};
			}
		}
		let res = await addTaskApi(formData.value);
		uni.hideLoading();
		if (res.code === 200) {
			uni.navigateTo({
				url: '/pages/subpackage/home/TaskManage/index'
			})
		}
	}

	onShow(() => {
		// 监听任务名称
		uni.$on("updateTask", function(data) {
			let chooseTask = JSON.parse(data.taskData);
			let num = chooseTask.targetNum ? chooseTask.targetNum : "";
			let unit = chooseTask.unit ?
				chooseTask.unit === "次数" ?
				"次" :
				"分钟" :
				"";
			formData.value.title = chooseTask.name + num + unit;
			formData.value.taskConfigId = chooseTask.taskConfigId;
			formData.value.targetNum = chooseTask.targetNum ?
				chooseTask.targetNum :
				undefined;
			isEmpty.value.title = false;
		});
		// 监听发送对象
		uni.$on("updateTaskSendObject", function(data) {
			let chooseSendArr = JSON.parse(data.list);
			formData.value.stuIdList = chooseSendArr;
			isEmpty.value.stuIdList = formData.value.stuIdList.length === 0;
		});
	});
	onLoad((option) => {
		pageType.value = option.pageType ? option.pageType : 2;
		uni.setNavigationBarTitle({
			title: pageType.value == 1 ? "查看任务" : "新增任务",
		});
		if (pageType.value == 1) {
			// 查看
			formData.value = JSON.parse(decodeURIComponent(option.details));
			tempRewardList.value = formData.value.rewardList;
		}
	});
	onUnload(() => {
		uni.$off();
	});
</script>

<style lang="scss" scoped>
	.task_item_page {
		.task_form {
			margin: 30rpx 30rpx 0;
			padding: 30rpx 30rpx 40rpx 30rpx;
			box-sizing: border-box;
			border-radius: 20rpx;
			color: #333;
			background-color: #fff;
			font-size: 30rpx;

			.form_item {
				margin-bottom: 30rpx;

				&_label {
					margin-bottom: 16rpx;
					font-weight: 500;
				}

				.date_range {
					position: relative;
					padding: 24rpx 20rpx;
					box-sizing: border-box;
					height: 90rpx;
					background-color: #f9f9fb;
					border-radius: 16rpx;

					.calendar_icon {
						position: absolute;
						right: 20rpx;
						width: 48rpx;
						height: 48rpx;
					}
				}

				&_con {
					position: relative;
					padding: 24rpx 20rpx;
					box-sizing: border-box;
					height: 90rpx;
					background-color: #f9f9fb;
					border-radius: 16rpx;

					.more_down {
						position: absolute;
						right: 20rpx;
						width: 30rpx;
						height: 30rpx;
					}
				}

				.must {
					color: red;
				}

				.input_bg {
					height: 90rpx;
					padding: 0 20rpx;
					box-sizing: border-box;
					background-color: #f9f9fb;
					border-radius: 16rpx;
				}

				.show {
					padding: 24rpx 20rpx;
				}

				.error {
					margin-top: 16rpx;
					font-size: 26rpx;
					color: #ff3d3d;
				}
			}
		}

		.footer {
			position: fixed;
			bottom: 0;
			width: 100%;
			height: 172rpx;
			left: 0;
			box-sizing: border-box;
			background-color: #fff;
			border-top: 1rpx solid #eee;

			button::after {
				border: none;
			}

			.btn-primary {
				margin-top: 16rpx;
				box-sizing: border-box;
				width: 440rpx;
				height: 90rpx;
				background-color: #615dff;
				color: #ffffff;
				border-radius: 20rpx;
				font-size: 30rpx;
				line-height: 90rpx;
			}
		}
	}
</style>